package com.hulk.dryad.common.util;

import com.google.common.base.Objects;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;
import org.springframework.context.MessageSource;
import org.springframework.validation.beanvalidation.MessageSourceResourceBundleLocator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Iterator;
import java.util.Set;



/**
 * @author hulk
 * @version 2020-2-27 上午1:15:24
 */
@Slf4j
public class ReqValidatorUtil {

    private static Validator validator = null;


    private synchronized static void loadValidatorInstance() {
        log.info("validator begin to load begin only one");
        if (validator == null) {
            log.info("validator begin to load instance");
			MessageSource messageSource = SpringContextHolder.getBean(MessageSource.class);
            validator = Validation.byDefaultProvider().configure()
                    .messageInterpolator(new ResourceBundleMessageInterpolator(
							new MessageSourceResourceBundleLocator(messageSource)))
                    .buildValidatorFactory().getValidator();
            log.info("validator load instance over");
        }

    }

	/** 验证某一个对象*/
    public static String validateBean(Object obj) {

        if (validator == null) {
            loadValidatorInstance();
        }
        StringBuilder buffer = new StringBuilder(64);
		/** 用于存储验证后的错误信息*/
        Set<ConstraintViolation<Object>> constraintViolations = validator
                .validate(obj);
		/** 验证某个对象,，其实也可以只验证其中的某一个属性的*/
        Iterator<ConstraintViolation<Object>> iter = constraintViolations
                .iterator();
        while (iter.hasNext()) {
            String message = iter.next().getMessage();
            buffer.append(message);
        }
        String validResp = buffer.toString().trim();
        if (!Objects.equal("", validResp)) {
            log.info("validator error: " + validResp);
        }
        return validResp;
    }





}
